import glob
import os
import numpy as np

from applications.utils.logger_utils import LoggerUtils
from collections import deque
import datetime
import time
import json
import threading
# import zlib
import cv2

from applications.utils.tcp_server import TCPServer
from applications.protocols.file_transfer_protocol import FileTransferProtocol
from applications.extensions.init_websocket import publish_msg

logger = LoggerUtils.get_logger("tcp_server_log")

os.makedirs("cache_data", exist_ok=True)





def start_data_servers(app) -> None:

    """
    启动激光雷达和IMU数据接收服务器
    以及数据保存线程
    """
    protocol = FileTransferProtocol()

    # 接收esp32数据
    def handle_receive_esp32_data(client_socket) -> None:

        message_type, data = protocol.receive_file(client_socket)
        if message_type == 0:
            return
        if len(data) == 0:
            # imu 心跳·
            logger.info(f"imu_client_heartbeat")
            return
        try:
            if message_type == 1:
                # 字符串类型，直接打印
                print(f"message_type: {message_type}")
                print(data.decode('utf-8'))
            elif message_type == 2:
                # 图片帧数据，先解压缩
                # try:
                #     decompressed_data = zlib.decompress(data)
                # except Exception as e:
                #     logger.error(f"图片数据解压失败: {str(e)}")
                #     return
                # 图片帧数据，使用cv2展示
                print(f"message_type: {message_type} (image frame)")
                # 尝试解码为图片（假设为jpg/png格式）
                img_array = np.frombuffer(data, dtype=np.uint8)
                img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
                if img is not None:
                    cv2.imshow('ESP32 Frame', img)
                    cv2.waitKey(1)
                else:
                    logger.error("无法解码图片帧数据")
            else:
                print(f"未知 message_type: {message_type}")
        except Exception as e:
            logger.error(f"处理IMU数据时出错: {str(e)}")

    # 启动IMU数据接收服务器
    server_imu = TCPServer(
        host=app.config.get("IMU_HOST"),
        port=8400,
        data_handler=handle_receive_esp32_data,
        server_name="ESP32_S3_SERVER",
    )
    server_imu.start()
